package com.lvmama.service.system.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.JedisCluster;

import com.alibaba.fastjson.JSONArray;
import com.lvmama.common.utils.DateUtil;
import com.lvmama.pojo.entity.rhino.Screen.OrderInfoData;
import com.lvmama.pojo.entity.rhino.Screen.Product;
import com.lvmama.service.system.HomeScreenService;

@Service("homeScreenService")
@Slf4j
public class HomeScreenServiceImpl implements HomeScreenService{

	@Autowired
    private JedisCluster jedisCluster;
	
	@Override
	public Map<String, Object> hotScenicSpot() {
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		 //订单总数
        Integer totalOrder = 0;
        if(jedisCluster.exists("rhino_orderList_size")){
            totalOrder = Integer.parseInt(jedisCluster.get("rhino_orderList_size"));
        }
        resultMap.put("totalOrderQuantity", totalOrder);

        //支付完成订单总数
        Integer totalPayOrder = 0;
        if(jedisCluster.exists("paid_rhino_orderList_size")){
        	totalPayOrder = Integer.parseInt(jedisCluster.get("paid_rhino_orderList_size"));
        }
        resultMap.put("totalPayOrder", totalPayOrder);
        
        if(!jedisCluster.exists("rhino_orderList") || !jedisCluster.exists("rhino_productList")){
            return resultMap;
        }
        //热门景区数据
        List<Product> productList = getProductList();
        if (productList == null || productList.size() == 0){
        	 return resultMap;
        }
        resultMap.put("productList", productList);
        //订单量数据
        List<OrderInfoData> orderList = getOrderList();
       
        Map<String,OrderInfoData> orderInfomap = new HashMap<String,OrderInfoData>();
        //合并重复数据
        for(OrderInfoData order : orderList){
            String province = order.getProvince();
            if(order.isPay()){
            	order.setPayCount(1l);
            }else{
            	order.setPayCount(0l);
            }
            if(orderInfomap.containsKey(province)){
            	OrderInfoData orderInfoData = orderInfomap.get(province);
            	orderInfoData.setCount(orderInfoData.getCount() + 1l );
            	orderInfoData.setPayCount(orderInfoData.getPayCount() + order.getPayCount());
            }else{
            	OrderInfoData orderInfoData = new OrderInfoData();
            	orderInfoData.setPayCount(order.getPayCount());
            	orderInfoData.setCount(1l);
            	orderInfoData.setProvince(province);
            	orderInfomap.put(province, orderInfoData);
            }
           
        }

        OrderInfoData unknownObj = new OrderInfoData();
        boolean unknownFlag0 = false;
        //生成新的list数组，省份与订单之间的关系
        List<OrderInfoData> newOrderInfoList = new ArrayList<OrderInfoData>();
        for(Map.Entry<String, OrderInfoData> entry : orderInfomap.entrySet()){
            String province = entry.getKey();
            if("".equals(province)){
                unknownObj.setProvince("未知");
                unknownObj.setCount(entry.getValue().getCount());
                unknownObj.setPayCount(entry.getValue().getPayCount());
                unknownFlag0 = true;
                continue;
            }
            entry.getValue().setProvince(matchProvince(province));
            newOrderInfoList.add(entry.getValue());
        }

        //根据订单量降序排序
        Collections.sort(newOrderInfoList,(s1, s2) -> s2.getCount().compareTo(s1.getCount()));
        
        //y轴省份城市 列表长度不能超过11
        List<String> orderProvinceList = new ArrayList<String>();
        //支付完成量 列表长度不能超过11
        List<Long> payCompleteList = new ArrayList<Long>();
        //订单量 列表长度不能超过11
        List<Long> orderQuantityList = new ArrayList<Long>();
        int index = 0;
        Long otherPayComplete = 0l;
        Long otherOrderQuantity = 0l;
        //订单占比
        List<Map<String, Object>> provinceSeriesMapList = new ArrayList<Map<String, Object>>();
        for (OrderInfoData orderInfoData : newOrderInfoList){
        	String province = orderInfoData.getProvince();
            Long amount = orderInfoData.getCount();
            Long payCount = orderInfoData.getPayCount();
            //当 index < 10 的时候 直接将城市 订单量 支付量加入对应的列表中
            if (index < 10){
            	 orderProvinceList.add(province);
                 payCompleteList.add(payCount);
                 orderQuantityList.add(amount);
                 index ++;
            }else{
                otherPayComplete +=  payCount;
                otherOrderQuantity +=  amount;
            }
            if (index < 7){
            	Map<String, Object> orderMap = new HashMap<String, Object>();
            	orderMap.put("name", province);
                orderMap.put("value", amount);
                provinceSeriesMapList.add(orderMap);
            }else{
            	Map<String, Object> orderMap = null;
            	if (index == 7){
            		orderMap = new HashMap<String, Object>();
                    orderMap.put("value", amount);
                    orderMap.put("name", "其他");
                    provinceSeriesMapList.add(6, orderMap);
            	}else{
            		orderMap = provinceSeriesMapList.get(6);
                    orderMap.put("value", Long.parseLong(orderMap.get("value").toString()) + amount);
            	}
            }
        }
        //当下标大于等于10表示  列表长度有11个
        if (index >= 10){
        	//第11个省份为其他
        	orderProvinceList.add("其他");
            payCompleteList.add(otherPayComplete);
            orderQuantityList.add(otherOrderQuantity);
        }
        
        //当订单中存在省份为空字符串时  列表的最后一个 订单省份设置为其他 订单总数和支付订单加上未知数
        if (unknownFlag0){
        	int size = orderProvinceList.size();
        	orderProvinceList.set(size - 1, "其他");
        	payCompleteList.set(size - 1, payCompleteList.get(size - 1) + unknownObj.getPayCount());
        	orderQuantityList.set(size - 1, orderQuantityList.get(size - 1) + unknownObj.getCount());
        	int mapListSize = provinceSeriesMapList.size();
        	Map<String, Object> orderMap = provinceSeriesMapList.get(mapListSize - 1);
        	orderMap.put("name", "其他");
        	orderMap.put("value", Long.parseLong(orderMap.get("value").toString()) + unknownObj.getCount());
        }

        resultMap.put("payComplete", payCompleteList);//支付完成量
        resultMap.put("orderQuantity", orderQuantityList);//订单量

        resultMap.put("provinceLegend", orderProvinceList);//Y轴省份
        resultMap.put("provinceSeries", provinceSeriesMapList);//省份的订单占比

        resultMap.put("newList", newOrderInfoList);//地图数据

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
        //根据订单时间分组
        Map<String, List<OrderInfoData>> collect = orderList.stream().peek(order->{
        	order.setOrderDateStr(sdf0.format(order.getOrderDate()));
        	
        }).collect(Collectors.groupingBy(OrderInfoData::getOrderDateStr));
        
        //统计各个时间组里 运营商的订单数
        List<OrderInfoData> newDateList= new ArrayList<OrderInfoData>();
        collect.forEach((date, list)->{
            OrderInfoData orderInfo = new OrderInfoData();
            list.forEach(orderInfoData -> {
            	 if("CM".equals(orderInfoData.getOperator())){
            		 orderInfoData.setCMOrderCount(1l);
                 }else if( "CU".equals(orderInfoData.getOperator())){
                	 orderInfoData.setCUOrderCount(1l);
                 }else if(  "CT".equals(orderInfoData.getOperator())){
                	 orderInfoData.setCTOrderCount(1l);
                 }else {
                	 orderInfoData.setOtherOrderCount(1l);
                 }
                long CMOrderCount = orderInfoData.getCMOrderCount() == null ? 0 : orderInfoData.getCMOrderCount();
                long CUOrderCount = orderInfoData.getCUOrderCount() == null ? 0 : orderInfoData.getCUOrderCount();
                long CTOrderCount = orderInfoData.getCTOrderCount() == null ? 0 : orderInfoData.getCTOrderCount();
                long OtherOrderCount = orderInfoData.getOtherOrderCount() == null ? 0 : orderInfoData.getOtherOrderCount();
                orderInfo.setCMOrderCount(orderInfo.getCMOrderCount() + CMOrderCount);
                orderInfo.setCUOrderCount(orderInfo.getCUOrderCount() + CUOrderCount);
                orderInfo.setCTOrderCount(orderInfo.getCTOrderCount() + CTOrderCount);
                orderInfo.setOtherOrderCount(orderInfo.getOtherOrderCount() + OtherOrderCount);

            });
            try {
                orderInfo.setOrderDate(sdf0.parse(date));
            } catch (Exception e) {
                e.printStackTrace();
            }
            newDateList.add(orderInfo);

        });
        
        Collections.sort(newDateList, (s1, s2) -> {
        	Long time1 = s1.getOrderDate().getTime();
        	Long time2 = s2.getOrderDate().getTime();
            return time1.compareTo(time2);
         });

        int listCount = newDateList.size();
        String[] orderTime = new String[listCount];
        Long[] CMOrder = new Long[listCount];
        Long[] CUOrder = new Long[listCount];
        Long[] CTOrder = new Long[listCount];
        Long[] otherOrder = new Long[listCount];
        for (int i=0 ;i < listCount; i++){
            Date date = newDateList.get(i).getOrderDate();
            String dateNowStr = sdf.format(date);
            orderTime[i]= dateNowStr;
            CMOrder[i] = newDateList.get(i).getCMOrderCount();
            CUOrder[i] = newDateList.get(i).getCUOrderCount();
            CTOrder[i] = newDateList.get(i).getCTOrderCount();
            otherOrder[i] = newDateList.get(i).getOtherOrderCount();
        }
        resultMap.put("orderTime", orderTime);//运营商订单X轴时间
        resultMap.put("CMOrder", CMOrder);//移动运营商订单量
        resultMap.put("CUOrder", CUOrder);//联通运营商订单量
        resultMap.put("CTOrder", CTOrder);//电信运营商订单量
        resultMap.put("otherOrder", otherOrder);//其他订单量


        //统计各个时间组里 省份的订单量
        List<String> dateList = new ArrayList<String>();
        collect.forEach((date, list)->{
        	dateList.add(date);
        	List<OrderInfoData> provinceOrderList = new ArrayList<OrderInfoData>();
        	//按省份分组
        	Map<String, List<OrderInfoData>> collect2 = list.stream().collect(Collectors.groupingBy(OrderInfoData::getProvince));
        	collect2.forEach((province ,orderDataList) ->{
        		OrderInfoData orderInfo = new OrderInfoData();
        		orderInfo.setProvince(province);
        		//统计订单量
        		orderInfo.setCount(orderDataList.stream().map(OrderInfoData::getCount).count());
        		try {
    				orderInfo.setOrderDate(sdf0.parse(date));

    			} catch (Exception e) {
    				e.printStackTrace();
    			}

        		provinceOrderList.add(orderInfo);
        	});
        	collect.put(date, provinceOrderList);
        });
        //根据下单时间升序排序
        Collections.sort(dateList, (s1, s2) -> s1.compareTo(s2));
        Map<String,List<Long>> dataMap = new HashMap<String,List<Long>>();
        Map<String,List<String>> provinceMap = new HashMap<String,List<String>>();

        for(String date : dateList){
        	List<OrderInfoData> orderInfoDataList = collect.get(date);
        	if (orderInfoDataList != null && orderInfoDataList.size() >0 ){
        		OrderInfoData unknownObj1 = new OrderInfoData();
        		boolean unknownFlag = false;
        		Iterator<OrderInfoData> it = orderInfoDataList.iterator();
            	index = 0;
            	//统计当某个时间点省份个数大于10的情况下 大于10的部分总和
            	Long count = 0L;
                while(it.hasNext()){
                	OrderInfoData order = it.next();
                    if("".equals(order.getProvince())){
                    	unknownFlag = true;
        				unknownObj1 = order;
                        it.remove();
                        continue;
                    }
                    if (index >= 10){
                    	count += order.getCount();
                    	it.remove();
                    }
                    index ++ ;
                }
                //当存在省份名称为空
        		if (unknownFlag){
        			count += unknownObj1.getCount();
        			//但处理后的订单列表大小刚好是10时 最后一个则改为其他
        			if(orderInfoDataList.size() == 10){
        				orderInfoDataList.get(9).setCount(orderInfoDataList.get(9).getCount() + count);
        				orderInfoDataList.get(9).setProvince("其他");
        			}else{
        				OrderInfoData orderInfoData = new OrderInfoData();
        				orderInfoData.setCount(count);
            			orderInfoData.setProvince("其他");
            			orderInfoDataList.add(orderInfoData);
        			}
        		}
        		
        		List<Long> countList = new ArrayList<Long>();
        		List<String> provinceList = new ArrayList<String>();
        		for (OrderInfoData orderInfoData : orderInfoDataList){
        			countList.add(orderInfoData.getCount());
        			provinceList.add(orderInfoData.getProvince());
        		}

                String dateNowStr = sdf.format(DateUtil.parse(date, DateUtil.PATTERN_YYYY_MM_DD_HHMMSS));
        		dataMap.put(dateNowStr, countList);
        		provinceMap.put(dateNowStr, provinceList);
        	}
        }
        
//        
        resultMap.put("XAxisList",orderTime);//时间轴
        resultMap.put("orderDataMap",dataMap);//订单统计数据
        resultMap.put("provinceMap",provinceMap);//省份数据
        return resultMap;
	}

	@Override
	public List<Product> getProductList() {
		List<String> dataList = jedisCluster.lrange("rhino_productList",0,-1);
		
        List<Product> resultList = new ArrayList<Product>();
        if (dataList == null || dataList.size() == 0){
        	return new ArrayList<Product>();
        }
        for(String str : dataList){
            JSONArray json = JSONArray.parseArray(str);
            if(json.size()!=0){
                for (int i=0;i<json.size();i++){
                    JSONArray childJson = JSONArray.parseArray(json.get(i).toString());
                    Product product = new Product();
                    product.setProductId(childJson.get(0).toString());
                    String productName = childJson.get(1).toString();
                    if("".equals(productName)){
                        continue;
                    }
                    product.setProductName(productName);
                    product.setViews(Long.valueOf(childJson.get(2).toString()));
                    resultList.add(product);
                }
            }
        }
        
        if (resultList == null || resultList.size() == 0){
        	return new ArrayList<Product>();
        }
        //排序
        Collections.sort(resultList, (s1, s2) -> s2.getViews().compareTo(s1.getViews()));
        int count = resultList.size() >40 ? 40 : resultList.size();
        return new ArrayList<Product>(resultList.subList(0,count));
	}

	@Override
	public List<OrderInfoData> getOrderList() {
        List<String> dataList = jedisCluster.lrange("rhino_orderList",0,-1);
        log.info("redis订单列表====" + dataList);
        List<OrderInfoData> list = new ArrayList<OrderInfoData>();
        for(String str : dataList){
            JSONArray json = JSONArray.parseArray(str);
            log.info("redis子订单====" + json);
            if(json.size()!=0){
                OrderInfoData orderInfoData = new OrderInfoData();
                orderInfoData.setProvince(json.get(0).toString());
                orderInfoData.setOperator(json.get(1).toString());
                if(json.get(2) instanceof Double){
                    orderInfoData.setAmount((Double) json.get(2));
                }else if (json.get(2)instanceof BigDecimal){
                    orderInfoData.setAmount(((BigDecimal) json.get(2)).doubleValue());
                } else {
                    orderInfoData.setAmount(new Double(json.get(2).toString()));
                }
                orderInfoData.setPayCount(Long.valueOf(json.get(3).toString()));
                orderInfoData.setCount(Long.valueOf(json.get(4).toString()));
                orderInfoData.setPay((boolean)json.get(5));
                orderInfoData.setOrderDate(DateUtil.parse(json.get(6).toString(), DateUtil.PATTERN_YYYY_MM_DD_HHMMSS));
                list.add(orderInfoData);
            }
        }
        return list;
	}

	private String matchProvince(String province){
        if(province.indexOf("宁夏")!=-1){
            province = "宁夏";
        }else if(province.indexOf("新疆")!=-1){
            province = "新疆";
        }else if(province.indexOf("内蒙古")!=-1){
            province = "内蒙古";
        }else if(province.indexOf("西藏")!=-1){
            province = "西藏";
        }else if(province.indexOf("广西")!=-1){
            province = "广西";
        }else if(province.indexOf("香港")!=-1){
            province = "香港";
        }else if(province.indexOf("澳门")!=-1){
            province = "澳门";
        }
        return province;
    }
}
